package cn.ymjr.sys.util;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.apache.commons.lang.StringUtils;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.net.URI;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * Created by tiny
 */
public class HttpClientUtil {


    public static String doPost(String url,String data) throws Exception{
        CloseableHttpClient httpclient = HttpClients.createDefault();
        String resData ="";
        try {
            HttpPost httpPost = new HttpPost(url);

            httpPost.addHeader("Connection", "keep-alive");
            httpPost.addHeader("Accept", "*/*");
            httpPost.addHeader("Content-type","application/json; charset=utf-8");
            httpPost.setEntity(new StringEntity(data, "UTF-8"));

            CloseableHttpResponse response = httpclient.execute(httpPost);

            // 请求结束，返回结果
             resData = EntityUtils.toString(response.getEntity());

        } catch (Exception e1) {
            e1.printStackTrace();
        }

        return resData;
    }
    public static String doGet(String url,Map<String, String> param)throws Exception{
        // 创建Httpclient对象
        CloseableHttpClient httpclient = HttpClients.createDefault();

        String resultDate = "";
        CloseableHttpResponse response = null;
        try {
            // 创建uri
            URIBuilder builder = new URIBuilder(url);
            if (param != null) {
                for (String key : param.keySet()) {
                    builder.addParameter(key, param.get(key));
                }
            }
            URI uri = builder.build();

            // 创建http GET请求
            HttpGet httpGet = new HttpGet(uri);

            // 执行请求
            response = httpclient.execute(httpGet);
            // 判断返回状态是否为200
            if (response.getStatusLine().getStatusCode() == 200) {
                resultDate = EntityUtils.toString(response.getEntity(), "UTF-8");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return resultDate;
    }
    /**
     * 获取快递详情post请求
     */
    public static String postData(String url, Map<String, String> params, String codePage){
        HttpClient httpClient = new HttpClient();
        httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(25 * 1000);
        httpClient.getHttpConnectionManager().getParams().setSoTimeout(30 * 1000);
        PostMethod method = new PostMethod(url);
        if(params !=null){
            method.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, codePage);
            method.setRequestBody(assembleRequestParams(params));
        }
        String result = "";
        try {
            httpClient.executeMethod(method);
            result = new String(method.getResponseBody(), codePage);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            method.releaseConnection();
        }
        return result;
    }
    /**
     * 组装http请求参数
     */
    private synchronized static NameValuePair[] assembleRequestParams(Map<String, String> data) {
        List<NameValuePair> nameValueList = new ArrayList<>();

        Iterator<Map.Entry<String, String>> it = data.entrySet().iterator();
        while (it.hasNext()) {
            Map.Entry<String, String> entry = (Map.Entry<String, String>) it.next();
            nameValueList.add(new NameValuePair((String) entry.getKey(), (String) entry.getValue()));
        }

        return nameValueList.toArray(new NameValuePair[nameValueList.size()]);
    }
    public static String doPostWithHeader(String url,String data,String header) throws Exception{
        CloseableHttpClient httpclient = HttpClients.createDefault();
        String resData ="";
        try {
            HttpPost httpPost = new HttpPost(url);

            httpPost.addHeader("Connection", "keep-alive");
            httpPost.addHeader("Accept", "*/*");
            httpPost.addHeader("Content-type","application/json; charset=utf-8");
            httpPost.addHeader("Authorization",header);
            if(StringUtils.isNotEmpty(data)){
                httpPost.setEntity(new StringEntity(data, "UTF-8"));
            }
            CloseableHttpResponse response = httpclient.execute(httpPost);

            // 请求结束，返回结果
            resData = EntityUtils.toString(response.getEntity());

        } catch (Exception e1) {
            e1.printStackTrace();
        }

        return resData;
    }
}
